/**
 * Copyright (c) 2016-2020 https://github.com/zhaohuatai
 *
 * contact 824069438@qq.com
 *  
 */
package org.zfes.snowy.ss.config.custom;

import java.lang.reflect.ParameterizedType;


import java.lang.reflect.Type;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import org.zfes.snowy.core.util.ZSerialUtil;


public class RedisCustomSerializer<T> implements RedisSerializer<T> {

	private String serializeType="fst";
	
	public RedisCustomSerializer(String serializeType) {
		super();
		this.serializeType = serializeType;
	}

	@Override
	public byte[] serialize(Object t) throws SerializationException {
		if(serializeType.equals("fst")){
			return ZSerialUtil.fstSerialize(t);
		}else if(serializeType.equals("jdk")){
			return ZSerialUtil.jdkSerialize(t);
		}else if(serializeType.equals("protstuff")){
			return ZSerialUtil.protstuffSerialize(t);
		}else if(serializeType.equals("kryo")){
			return ZSerialUtil.kryoSerialize(t);
		}else if(serializeType.equals("hessian")){
			return ZSerialUtil.hessianSerialize(t);
		}
		return ZSerialUtil.jdkSerialize(t);
	}

	@SuppressWarnings("unchecked")
	@Override
	public T deserialize(byte[] bytes) throws SerializationException {
		if(serializeType.equals("fst")){
			return (T) ZSerialUtil.fstDeserialize(bytes);
		}else if(serializeType.equals("jdk")){
			return (T) ZSerialUtil.jdkDeserialize(bytes);
		}else if(serializeType.equals("protstuff")){
			Class<?> clz = this.getClass();
			ParameterizedType type = (ParameterizedType) clz.getGenericSuperclass();
			Type[] types = type.getActualTypeArguments();
			Class<?> cls = (Class<T>) types[0];
			return (T) ZSerialUtil.protstuffDeserialize(bytes,  cls);
		}else if(serializeType.equals("kryo")){
			return (T) ZSerialUtil.kryoDeserialize(bytes);
		}else if(serializeType.equals("hessian")){
			return (T) ZSerialUtil.hessianDeserialize(bytes);
		}
		return (T) ZSerialUtil.jdkDeserialize(bytes);
	}

}
